package com.sinocare.project.maintenance.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinocare.project.common.entity.SncUserLogin;
import com.sinocare.project.maintenance.service.SncUserLoginService;
import com.sinocare.project.maintenance.service.impl.SncUserLoginServiceImpl;
import com.sinocare.project.maintenance.util.ApplicationContextUtils;
import com.sinocare.project.common.util.SaltUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

/**
 * 自定义密码比较规则
 *
 */
public class CustomCredentialsMatcher  extends SimpleCredentialsMatcher{

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        SncUserLoginService sncUserLoginService= (SncUserLoginService) ApplicationContextUtils.getBean("sncUserLoginService");
        UsernamePasswordToken uToken = (UsernamePasswordToken)token;
        //前台传入的密码
        String password  =  new String(uToken.getPassword());
        //前台传入的用户名
        String username = uToken.getUsername();
        SncUserLogin userLogin = new SncUserLogin();
        userLogin.setName(username);
        userLogin.setPassword(password);
        //获取数据库存放的密码和加密规则
        String dbPassword = (String) info.getCredentials();
        QueryWrapper<SncUserLogin> wrapper = new QueryWrapper<>();
        wrapper.eq("count",username);
        SncUserLogin one = sncUserLoginService.getOne(wrapper);
        if(one!=null){
            if (one.getStatus()==1){
                String[] split = one.getPassword().split(",");
                String s = split[2];
                int i = Integer.parseInt(s);
                password= SaltUtil.getPassword(password,split[1],i);
                System.out.println("password"+password);
                System.out.println("dbpassword"+dbPassword);
                return this.equals(password,dbPassword);
            }else throw new AuthenticationException();
        }
        throw new UnknownAccountException();
    }

}
